// ======================================================================
// ======================== 模块导入区 =================================
// ======================================================================

import { getUrlParam } from './utils';
import initReport from './ads_report';
import BeylaCls from './beyla_report';

// ======================================================================
// ======================== 基础功能区 =================================
// ======================================================================

// 移动端 rem 适配逻辑
{
  function setRem() {
    const baseSize = 10;
    const scale = document.documentElement.clientWidth / 375;
    document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px';
  }
  setRem();
  window.addEventListener('resize', setRem);
}

// 从 URL 获取并设置全局的 portal/channel ID
const portal = (window._portal = getUrlParam('channel') || getUrlParam('portal'));

// ======================================================================
// ==================== 各追踪服务初始化函数区 ===========================
// ======================================================================

function initGA() {
  const gaConfig = window.curPortalConfig?._reports?.ga;
  const ID = gaConfig?.key;

  if (!ID) {
    console.warn('Google Analytics ID not configured in config.js (_reports.ga.key)');
    return;
  }

  const script = document.createElement('script');
  script.src = `https://www.googletagmanager.com/gtag/js?id=${ID}`;
  script.async = true;
  document.head.append(script);
  script.onload = () => {
    window.dataLayer = window.dataLayer || [];
    function gtag() {
      window.dataLayer.push(arguments);
    }
    window.gtag = gtag;
    gtag('js', new Date());
    gtag('config', ID);
  };
}

function initTT() {
  const ttConfig = window.curPortalConfig?._reports?.tt;
  const ID = ttConfig?.key;

  if (!ID) {
    console.warn('TikTok Pixel ID not configured in config.js (_reports.tt.key)');
    return;
  }
  
  /* eslint-disable */
  !(function (w, d, t) {
    w.TiktokAnalyticsObject = t;
    var ttq = (w[t] = w[t] || []);
    (ttq.methods = [
      'page', 'track', 'identify', 'instances', 'debug', 'on', 'off', 'once', 'ready', 'alias',
      'group', 'enableCookie', 'disableCookie', 'holdConsent', 'revokeConsent', 'grantConsent',
    ]),
    (ttq.setAndDefer = function (t, e) {
      t[e] = function () {
        t.push([e].concat(Array.prototype.slice.call(arguments, 0)));
      };
    });
    for (var i = 0; i < ttq.methods.length; i++) ttq.setAndDefer(ttq, ttq.methods[i]);
    (ttq.instance = function (t) {
      for (var e = ttq._i[t] || [], n = 0; n < ttq.methods.length; n++)
        ttq.setAndDefer(e, ttq.methods[n]);
      return e;
    }),
    (ttq.load = function (e, n) {
      var r = 'https://analytics.tiktok.com/i18n/pixel/events.js';
      (ttq._i = ttq._i || {}), (ttq._i[e] = []), (ttq._i[e]._u = r),
      (ttq._t = ttq._t || {}), (ttq._t[e] = +new Date()), (ttq._o = ttq._o || {}), (ttq._o[e] = n || {});
      var o = document.createElement('script');
      (o.type = 'text/javascript'), (o.async = !0), (o.src = r + '?sdkid=' + e + '&lib=' + t);
      var a = document.getElementsByTagName('script')[0];
      a.parentNode.insertBefore(o, a);
    });

    ttq.load(ID);
    ttq.page();
  })(window, document, 'ttq');
  /* eslint-enable */
}

function initFB() {
  const fbConfig = window.curPortalConfig?._reports?.fb;
  const ID = fbConfig?.key;

  if (!ID) {
    console.warn('Facebook Pixel ID not configured in config.js (_reports.fb.key)');
    return;
  }

  /* eslint-disable */
  !(function(f, b, e, v, n, t, s) {
    if (f.fbq) return;
    n = f.fbq = function() {
      n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments);
    };
    if (!f._fbq) f._fbq = n;
    n.push = n;
    n.loaded = !0;
    n.version = '2.0';
    n.queue = [];
    t = b.createElement(e);
    t.async = !0;
    t.src = v;
    s = b.getElementsByTagName(e)[0];
    s.parentNode.insertBefore(t, s);
  })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
  
  fbq('init', ID);
  fbq('track', 'PageView');
  /* eslint-enable */
}

function initBeyla() {
  window._BeylaCls = new BeylaCls();
  window._BeylaCls._logInit();
}

// ======================================================================
// ================= 广告和追踪服务的“总控制器” ==========================
// ======================================================================
{
  window._adsLoaded = () => {
    window._adsLoaded = () => Promise.resolve(); // 确保 Promise 只被创建一次
    return new Promise((resolve) => {
      let flag = 0;
      const onFurther = () => {
        flag += 1;
        // 只有当 AdSense 主脚本 和 config.js 都加载完成后才执行
        if (flag === 2) {
          console.log('AdSense and Config scripts loaded. Initializing all tracking services...');
          
          // 在这里调用所有依赖配置的初始化函数
          initGA();
          initTT();
          // initFB();
          initReport();
          
          resolve(); // 通知 HomePage.vue 可以开始加载广告了
        }
      };

      // 1. 等待 AdSense 主脚本加载
      if (window.adsbygoogle) {
        onFurther();
      } else {
        const _adsEle = document.getElementById('_adsEle');
        if (_adsEle) {
          _adsEle.onload = () => onFurther();
          _adsEle.onerror = () => {
            console.error("AdSense主脚本加载失败。");
            onFurther(); // 即使失败，也继续流程，避免阻塞
          };
        } else {
          onFurther();
        }
      }
      
      // 2. 等待 config.js 加载并解析
      const takeFn = () => {
        try {
          window.portalConfig = window.portalConfig || {};
          
          // 健壮的配置选择逻辑
          const configKey = portal || location.hostname;
          let config = window.portalConfig[configKey];

          if (!config) {
            console.warn(`在 config.js 中未找到 key 为 '${configKey}' 的配置, 尝试备用key '1'。`);
            config = window.portalConfig['1'];
          }
          if (!config) {
            const firstKey = Object.keys(window.portalConfig)[0];
            if(firstKey) {
                console.warn(`在 config.js 中也未找到备用 key '1', 将使用第一个找到的配置: '${firstKey}'。`);
                config = window.portalConfig[firstKey];
            }
        }

          window.curPortalConfig = config || {};
          console.log("当前使用的配置 (curPortalConfig):", window.curPortalConfig);
          
        } catch (e) {
          console.error("解析 config.js 时出错:", e);
          window.curPortalConfig = {};
        } finally {
          onFurther();
        }
      };

      if (typeof portalConfig === 'object' && Object.keys(portalConfig).length > 0) {
        takeFn();
      } else {
        const _configEle = document.getElementById('_configEle');
        if (_configEle) {
          _configEle.onload = () => takeFn();
          _configEle.onerror = () => {
            console.error("config.js 文件加载失败 (404或CORS错误)。");
            takeFn(); // 即使失败，也执行 takeFn 以免阻塞
          };
        } else {
          console.error("在 index.html 中未找到 id 为 '_configEle' 的 script 标签。");
          takeFn();
        }
      }
    });
  };
}

// ======================================================================
// ====================== 初始启动逻辑 =================================
// ======================================================================

// 1. 立即启动不依赖配置的内部行为追踪
initBeyla();

// 2. 启动广告和营销追踪的加载流程
window._adsLoaded();